//
//  UITextView+Mango.m
//  Mango
//
//  Created by 胡超 on 2021/1/25.
//  Copyright © 2021年 胡超., ltd. All rights reserved.
//

#import <objc/runtime.h>

#import "UITextView+Mango.h"

@interface UITextView () <UITextViewDelegate>

@end

@implementation UITextView (Mango)

- (void)setLineSpacing:(CGFloat)lineSpacing {
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = lineSpacing;
    style.alignment = self.textAlignment;
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:self.text?:@"" attributes:@{
        NSForegroundColorAttributeName: self.textColor?:UIColor.whiteColor,
        NSFontAttributeName: self.font?:[UIFont systemFontOfSize:14],
        NSParagraphStyleAttributeName: style,
    }];
    self.attributedText = attributedText;
}

#pragma mark - Text Action

- (NSMutableDictionary *)mm_textActions {
    NSMutableDictionary *mm_textActions = objc_getAssociatedObject(self, _cmd);
    if (mm_textActions == nil) {
        mm_textActions = [[NSMutableDictionary alloc] init];
        objc_setAssociatedObject(self, _cmd, mm_textActions, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return mm_textActions;
}

- (void)setText:(NSString *)text action:(void(^)(void))action {
    [self setText:text textColor:nil action:action];
}

- (void)setText:(NSString *)text textColor:(UIColor *)textColor action:(void(^)(void))action {
    if (text.length == 0 || !action)
        return;
    
    NSMutableAttributedString *attributedText = nil;
    if (self.attributedText) {
        attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    } else if (self.text) {
        attributedText = [[NSMutableAttributedString alloc] initWithString:self.text attributes:@{
            NSForegroundColorAttributeName: self.textColor?:UIColor.blackColor,
            NSFontAttributeName: self.font ?: [UIFont systemFontOfSize:14],
        }];
    } else {
        return;
    }
    NSRange range = [attributedText.string rangeOfString:text];
    if (range.location == NSNotFound)
        return;
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"textaction://range=%ld,%ld",range.location,range.length]];
    [attributedText addAttributes:@{
        NSForegroundColorAttributeName: textColor?:UIColor.systemBlueColor,
        NSLinkAttributeName: url,
    } range:range];
    [self.mm_textActions setObject:action forKey:url];
    
    self.delegate = self;
    self.editable = NO;
    self.dataDetectorTypes = UIDataDetectorTypeNone;
    self.linkTextAttributes = @{};
    self.attributedText = attributedText;
}

#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    void(^action)(void) = [self.mm_textActions objectForKey:URL];
    if (action) {
        action();
    }
    return NO;
}

@end
